<?php


namespace app\home\controller;


use app\base\BaseController;
use think\Exception;
use think\facade\Db;
use think\facade\View;

class InventoryIn extends BaseController
{
    protected $title='盘存入库';
    protected $table='stock_order';
    protected $tableMx='stock_order_detail';
    protected $sType=5;
    public function index()
    {
        $param=$this->param;
        if (request()->isAjax()) {

            $where[]=['so.type','=',$this->sType];
            $where[]=['so.status','>','-1'];
            $where[]=['sod.status','>','-1'];
            if (isset($param['sureName'])&&$param['sureName']){
                $where[]=['a.name','like','%'.$param['sureName']."%"];
            }
            if (isset($param['times'])&&$param['times']){
                $tiems=explode('~',$param['times']);
                $where[]=['so.checkTime','between',[$tiems[0].' 00:00:00',$tiems[0].' 23:59:59']];
            }
            foreach (['buyCode','name','brand','specs'] as $v){
                if (isset($this->param[$v])&&$this->param[$v]){
                    $where[]=['md.'.$v,'like','%'.$this->param[$v].'%'];
                }
            }
            if (isset($param['orderNum'])&&$param['orderNum']){
                $where[]=['so.orderNum','like','%'.$param['orderNum']."%"];
            }
            if (isset($param['status'])&&$param['status']){
                $where[]=['so.status','=',$param['status']];
            }
            $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];
            $list=Db::name('stock_order_detail')
                ->alias('sod')
                ->leftJoin('stock_order so','so.id=sod.orderId')
                ->leftJoin('admin a','a.id=so.checkId')
                ->leftJoin('material_dossier md','md.id=sod.mdId')
                ->where($where)
                ->field("sod.*,a.name as sureName,so.checkTime,so.remark,so.status as orderStatus,so.orderNum,md.name as mdName,md.specs,md.brand,md.buyCode,unit")
                ->order('so.id DESC')->paginate($rows);
            return table_assign(0, '操作成功', $list);
        } else {
            return view();
        }

    }

    public function add()
    {
        $param = get_params();
        if (request()->isAjax()) {
            $postData = $this->param;
            $id=$this->param['id']??'';
            $mx=$param['mx']??[];
            if (!$mx){
                return  to_assign(1,'参数缺失');
            }
            $mxId=$mx['mxid']??[];
            $mdId=$mx['mdId']??[];
            $num=$mx['num']??[];
            $sodPrice=$mx['sodPrice']??[];
            if (!$mdId){
                return  to_assign(1,'参数缺失');
            }
            $postData['orderNum']=dJBHBySql($this->table,'orderNum',getOrderPrefix($this->controller).date('Ymd'),false,1000);
            $postData['update_time']=time();
            Db::startTrans();
            try {
                if ($id){
                    Db::name($this->table)->strict(false)->field(true)->update($postData);
                    add_log('edit', $param['id'], $this->param,$this->title);
                }else{
                    $postData['createId']=$this->uid;
                    $postData['departId']=$this->did;
                    $postData['type']=$this->sType;
                    $postData['create_time']=time();
                    $id = Db::name($this->table)->strict(false)->field(true)->insertGetId($postData);
                    add_log('add', $id, $this->param,$this->title);
                }
                foreach ($mdId as $key=> $m){
                    $mxData=[
                        'orderId'=>$id,
                        'mdId'=>$mdId[$key],
                        'wId'=>1,
                        'thisId'=>0,
                        'num'=>$num[$key],
                        'kcNum'=>0,
                        'occupyNum'=>0,
                        'sodPrice'=>$sodPrice[$key],
                        'sodType'=>$sodType[$key]??5,
                        'type'=>$this->sType,
                        'create_time'=>time(),
                        'update_time'=>time()
                    ];
                    if (isset($mxId[$key])&&$mxId[$key]){
                        unset($mxData['create_time']);
                        $mxData['id']=$mxId[$key];
                    }
                    Db::name($this->tableMx)->save($mxData);
                }
                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                return to_assign(1,'操作失败：'.$e->getMessage());
            }


            return to_assign();
        } else {
            $id = isset($param['id']) ? $param['id'] : 0;
            $mxList=[];
            if ($id > 0) {
                $detail = Db::name($this->table)->where('id', $id)->field("*,(select name from fy_admin a where a.id=checkId)username")->find();
                $mxList=Db::name($this->tableMx)
                    ->alias('sod')
                    ->leftJoin('material_dossier md','md.id=sod.mdId')
                    ->where('sod.status','>',-1)
                    ->where('sod.orderId',$id)
                    ->field('sod.*,md.name,md.brand,md.specs,md.buyCode,md.unit')
                    ->select();
            }else{
              $orderNum=dJBHBySql($this->table,'orderNum',getOrderPrefix($this->controller).date('Ymd'),false,1000);
                $detail=['orderNum'=>$orderNum];
            }
            View::assign('detail', $detail);
            View::assign('mxList', $mxList);
            View::assign('id', $id);
            return view('form');
        }
    }

    public function addMx()
    {
        if (request()->isPost()) {
            $where[]=['status','=',1];
            foreach (['buyCode','name','brand','specs'] as $v){
                if (isset($this->param[$v])&&$this->param[$v]){
                    $where[]=[$v,'like','%'.$this->param[$v].'%'];
                }
            }
            $limit=$this->param['limit']??15;
            $list=Db::name('material_dossier')
                ->where($where)
                ->paginate($limit);
            return table_assign(0, '', $list);
        } else {
            return view('mx');
        }
    }
    public function removeMx()
    {
        $id = $this->param['id'];
        try {
            Db::name($this->tableMx)->where('id', $id)->update(['status' => -1, 'update_time' => time(), 'deleted' => time()]);
            add_log('delete', $id, $this->param, $this->title);
        } catch (\Exception $e) {
            return to_assign(1, '删除失败:' . $e->getMessage());
        }
        return to_assign();
    }
    public function delete()
    {
        if (request()->isDelete()) {
            $id = get_params("id");
            $status = Db::name($this->table)->where('id', 'in', $id)->column('status');
            if (in_array('2', $status)) {
                return to_assign(1, "有已确认数据，不能删除");
            }
            Db::startTrans();
            try {
                Db::name($this->table)->where('id', 'in', $id)->update(['status' => -1, 'deleted' => time()]);
                Db::name($this->tableMx)->where('orderId', 'in', $id)->update(['status' => -1, 'deleted' => time()]);
                add_log('delete', $id, request()->param(), $this->title);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return to_assign(1, "删除失败" . $e->getMessage());
            }
            return to_assign(0, "删除成功");
        } else {
            return to_assign(1, "错误的请求");
        }
    }
    public function onSure()
    {
        $id=$this->param['id']??0;
        if (!$id){
            return to_assign(1,'参数缺失');
        }
        $status=Db::name($this->table)->where('id',$id)->value('status');
        if ($status!=1){
            return to_assign(1,'参数有误');
        }
        $mx=Db::name($this->tableMx)->where('status',1)->where('orderId',$id)->count();
        if (!$mx){
            return to_assign(1,'请添加明细');
        }
        Db::startTrans();
        try {
            Db::name($this->table)->where('id',$id)->update([
                'checkId'=>$this->uid,
                'checkTime'=>date('Y-m-d H:i:s'),
                'status'=>2,
                'update_time'=>time()]);
            Db::name($this->tableMx)->where('status',1)
                ->where('orderId',$id)->update(['status'=>2,'update_time'=>time()]);
            add_log('onSure', $id, $this->param,$this->title);
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            return to_assign(1,'操作失败:'.$e->getMessage());
        }
        return to_assign(0,'操作成功');
    }

    public function info($id)
    {

            $detail = Db::name($this->table)->where('id', $id)->field("*,(select name from fy_admin a where a.id=checkId)username")->find();
            $mxList=Db::name($this->tableMx)
                ->alias('sod')
                ->leftJoin('material_dossier md','md.id=sod.mdId')
                ->where('sod.status','>',-1)
                ->where('sod.orderId',$id)
                ->field('sod.*,md.name,md.brand,md.specs,md.buyCode,md.unit')
                ->select();
        View::assign('detail', $detail);
        View::assign('mxList', $mxList);
        View::assign('id', $id);
        return view('info');
    }

    public function onCancel()
    {
        $id=$this->param['id']??0;
        if (!$id){
            return to_assign(1,'参数缺失');
        }
        $info=Db::name($this->table)->where('id',$id)->find();
        if (!$info||$info['status']!=2){
            return to_assign(1,'参数有误');
        }
        $mxList= Db::name($this->tableMx)
            ->alias('sod')
            ->where('orderId',$id)->where('status','>',-1)
        ->field("*,
        (select count(*) from fy_sale_contract_lock scl where scl.stockOrderDetailId = sod.id and scl.status >-1) hasLock,
        (select count(*) from fy_stock_order_detail sod1 where sod1.thisId=sod.id and sod1.status>-1) hasCk")
            ->select();
        Db::startTrans();
        try {
            Db::name($this->table)->where('id',$id)->update([
                'checkId'=>$this->uid,
                'checkTime'=>date('Y-m-d H:i:s'),
                'status'=>1,
                'update_time'=>time()]);

            $mxIds=[];
            foreach ($mxList as $ml){
                $ml['hasLock']=$ml['hasLock']??0;
                $ml['hasCk']=$ml['hasCk']??0;
                if ($ml['hasLock']>0){
                    throw new Exception('已有锁定数据，请删除后再撤销');
                }
                if ($ml['hasCk']>0){
                    throw new Exception('已有出库单据数据，请删除后再撤销');
                }
                $mxIds[]=$ml['id'];
            }
            if ($mxIds){
                Db::name($this->tableMx)->where('id','in',$mxIds)->update(['status'=>1,'update_time'=>time(),'sodStatus'=>1,'refundStatus'=>1]);
            }
            add_log('back', $id, $this->param,$this->title);
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            return to_assign(1,'操作失败:'.$e->getMessage());
        }
        return to_assign(0,'操作成功');
    }
}